package WebRoot.demo5.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.bson.Document;
import org.hoyi.dishop.Hoyipage;
import org.hoyi.nosql.mongo.HoyiMongoCluster;
import org.hoyi.wb.comment.RequestMode;
import org.hoyi.wb.comment.RequestType;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.client.AggregateIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Aggregates;
import com.mongodb.client.model.Filters;
import com.mongodb.util.JSON;

@RequestMode(MODE = { RequestType.GET, RequestType.POST })
public class MongodbDemo extends Hoyipage {

	// mongodb 存与取
	@RequestMode(MODE = { RequestType.POST, RequestType.GET })
	public void mongodbListTest() {
		DBCollection collection = HoyiMongoCluster.getDatabase("nadmin").getCollection("user");

		DBObject dbObject = new BasicDBObject();
		dbObject.put("age1", "30");
		collection.save(dbObject);

		DBCursor cursor = collection.find();
		this.WriteUTF8JSONDATAMSG(1, "success", cursor.toArray());
	}

	// mongodb 获取单文档
	@RequestMode(MODE = { RequestType.POST, RequestType.GET })
	public void mongodbDocumentTest() {

		MongoDatabase mongoDatabase = HoyiMongoCluster.getMongoClient().getDatabase("nadmin");
		MongoCollection<Document> collection = mongoDatabase.getCollection("user");

		AggregateIterable<Document> iterable = collection
				.aggregate(Arrays.asList(Aggregates.unwind("$a"), Aggregates.match(Filters.eq("a.name", "Tom"))));

		ArrayList<Map<String, String>> lists = new ArrayList<>();
		MongoCursor<Document> cursor = iterable.iterator();
		while (cursor.hasNext()) {
			Document user = cursor.next();
			String jsonString = user.toJson();
			Map<String, String> jsonStrToMap = jsonStrToMap(jsonString);
			lists.add(jsonStrToMap);
		}

		this.WriteUTF8JSONDATAMSG(1, "success", lists);

	}

	/*
	 * 插入
	 */
	@RequestMode(MODE = { RequestType.GET, RequestType.POST })
	public void insertMongodb(String ordersId, String uxId, String orderNum, String note, String userId)
			throws Exception {
		OrdersDto ordersDto = new OrdersDto();
		ordersDto.setId(ordersId);
		ordersDto.setUxid(uxId);
		ordersDto.setOrdernum(orderNum);
		ordersDto.setNote(note);
		ordersDto.setUserId(userId);
		MongodbUtil.insertMany(MongodbUtil.ObjTransformToDoc(ordersDto), "orders");
		this.WriteUTF8JSONDATAMSG(1, "sucess", ordersDto);
	}

	/**
	 * 更新
	 * 
	 * @param ordersId
	 * @param note
	 * @throws Exception
	 */
	@RequestMode(MODE = { RequestType.GET, RequestType.POST })
	public void updateMongodb(String ordersId, String note) throws Exception {
		Document filter = new Document();
		filter.put("id", ordersId);

		Document update = new Document();
		update.put("$set", new Document("note", note));

		MongodbUtil.updateOne(filter, update, "orders");

		this.WriteUTF8JSONDATAMSG(1, "sucess", note);
	}

	/**
	 * 列表
	 * 
	 * @param pageIndex
	 * @param pageSize
	 * @throws Exception
	 */
	@RequestMode(MODE = { RequestType.GET, RequestType.POST })
	public void listMongodb(String pageIndex, String pageSize) throws Exception {
		// filter.put("id", ordersId);
		//
		// Document update = new Document();
		// update.put("$set", new Document("note", note));

		List<Map<String, String>> list = MongodbUtil.findPage("orders", new Document(),
				Integer.valueOf(pageIndex), Integer.valueOf(pageSize), new Document());

		this.WriteUTF8JSONDATAMSG(1, "sucess", list);
	}
	
	/**
	 * 列表
	 * 
	 * @param pageIndex
	 * @param pageSize
	 * @throws Exception
	 */
	@RequestMode(MODE = { RequestType.GET, RequestType.POST })
	public void deleteMongodb(String note) throws Exception {
		// filter.put("id", ordersId);
		//
		// Document update = new Document();
		// update.put("$set", new Document("note", note));

//		List<Map<String, String>> list = MongodbUtil.findPage("orders", new Document("note", "note"),
//				Integer.valueOf(pageIndex), Integer.valueOf(pageSize), new Document());
		
		MongodbUtil.delete("orders", new Document("note", note));

		this.WriteUTF8JSONDATAMSG(1, "sucess", "");
	}

	// @RequestMode(MODE = { RequestType.GET, RequestType.POST })
	// public void insertMongodbOrderByUser(String ordersId, String uxId, String
	// orderNum, String note, String userId)
	// throws Exception {
	// OrdersDto ordersDto = new OrdersDto();
	// ordersDto.setId(ordersId);
	// ordersDto.setUxid(uxId);
	// ordersDto.setOrdernum(orderNum);
	// ordersDto.setNote(note);
	// ordersDto.setUserId(userId);
	//
	// Document document = MongodbUtil.ObjTransformToDoc(ordersDto);
	// Document orderDocument = new Document();
	// orderDocument.append("orders", document);
	// orderDocument.append("userId", userId);
	//
	// MongodbUtil.insertMany(orderDocument, "userOrders");
	// this.WriteUTF8JSONDATAMSG(1, "sucess", ordersDto);
	// }
	//
	// /**
	// * 查找并更新
	// *
	// * @param ordersId
	// * @param uxId
	// * @param orderNum
	// * @param note
	// * @param userId
	// * @throws Exception
	// */
	// @RequestMode(MODE = { RequestType.GET, RequestType.POST })
	// public void addMoreMongodbOrderByUser(String ordersId, String uxId, String
	// orderNum, String note, String userId)
	// throws Exception {
	// OrdersDto ordersDto = new OrdersDto();
	// ordersDto.setId(ordersId);
	// ordersDto.setUxid(uxId);
	// ordersDto.setOrdernum(orderNum);
	// ordersDto.setNote(note);
	// ordersDto.setUserId(userId);
	//
	// Document document = MongodbUtil.ObjTransformToDoc(ordersDto);
	//
	// Document filter = new Document();
	// filter.put("userId", userId);
	//
	// MongoCollection<Document> collection =
	// MongodbUtil.getCollection("userOrders");
	// Document findDoc = collection.find(filter).first();
	// findDoc.append("orders", document);
	//
	// Document update = new Document();
	// update.put("$set", findDoc);
	//
	// MongodbUtil.updateOne(filter, findDoc, "userOrders");
	// this.WriteUTF8JSONDATAMSG(1, "sucess", ordersDto);
	// }

	// mongodb 满足附近经纬度的数据
	@RequestMode(MODE = { RequestType.POST, RequestType.GET })
	public void mongodbNearBy() {
		double lat = Double.valueOf(this.getParams("lat"));
		double lon = Double.valueOf(this.getParams("lon"));
		double radius = Double.valueOf(this.getParams("radius"));
		DBCollection collection = HoyiMongoCluster.getDatabase("admin").getCollection("mapinfo");
		List<DBObject> locList = getDBObjectByLocation(collection, lat, lon, radius);
		this.WriteUTF8JSONDATAMSG(1, "success", locList);
	}

	private static List<DBObject> getDBObjectByLocation(DBCollection col, double longitude, double latitude,
			double radius) {
		BasicDBList point = new BasicDBList();
		point.add(longitude);
		point.add(latitude);
		Double distance = radius / 6378100;
		BasicDBList centerSphere = new BasicDBList();
		centerSphere.add(point);
		centerSphere.add(distance);
		BasicDBObject location = new BasicDBObject("$geoWithin", new BasicDBObject("$centerSphere", centerSphere));
		BasicDBObject query = new BasicDBObject("loc", location);
		DBCursor cursor = col.find(query);
		List<DBObject> cursors = cursor.toArray();
		return cursors;
	}

	public static Map<String, String> jsonStrToMap(String jsonString) {
		Object parseObj = JSON.parse(jsonString); // 反序列化 把json 转化为对象
		Map<String, String> map = (Map<String, String>) parseObj; // 把对象转化为map
		return map;
	}

}
